<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

use \FormatValidator;

// require __DIR__.'/../bootstrap/autoload.php';

use SmsUtils;

use PDOManager;
use Lang2;
use Illuminate\Support\Facades\Log;

// define(APP_BASE, "/htdocs/tt201801/");
//require_once "/htdocs/tt201801/app/Http/Controllers/SignatureHelper.php";

//require_once "/htdocs/tt201801/app/Http/Controllers/sms/TopSdk.php";
//use TopClient;
//use AlibabaAliqinFcSmsNumSendRequest;
//
//use Aliyun\DySDKLite\SignatureHelper;

class UserMgmrController extends Controller{

//    public function pageLogin(){
//		return view('user.login', ['name' => 'seven']);
//    }

	function generate_code($length = 6) {
		return rand(pow(10,($length-1)), pow(10,$length)-1);
	}
	public function requestVerifyCode(Request $request){
		$username = $request->input('phone');

        $check_result = FormatValidator::from($username)
                    ->isNotEmpty(3, "手机号不能为空")
                    ->isMobile(4, "请填入有效的手机号")
                    ->validate();
        if($check_result){
            $result_arr = array(
                'code'=>$check_result["code"],
                'msg'=>$check_result["message"]
            );
            return response()->json($result_arr);
        }

		$result_arr = array();

        $code = $this->generate_code(6);
        $res = SmsUtils::sendSms($username, $code);

        if($res->code != 0){
            //"sub_code":"isv.BUSINESS_LIMIT_CONTROL"
            $msg = null;
            if($res["sub_code"] == "isv.BUSINESS_LIMIT_CONTROL"){
                $msg = "请求过于频繁";
            }else{
                $msg = "获取验证码失败";
            }

            $result_arr = array(
                'code'=>5,
                'msg'=>$msg,
                'result'=>$res["sub_code"]
            );
            return response()->json($result_arr);
        }else{
            DB::table('verify_code')->where('username', '=', $username)->delete();

            ///插入数据
            DB::table('verify_code')->insert([
                'username'=>$username,
                'code'=>$code . "",
                'createTime'=>time() . "",
                'expireTime'=>(60 + time()) . ""
            ]);

            $result_arr = array(
                'code'=>0,
                'msg'=>""
            );
            return response()->json($result_arr);
        }


	}




	public function registV1(Request $request){
		$username = $request->input('username');
		$password = $request->input('password');
        $nickname = $request->input('nickname');
		$code = $request->input('code');

		$result_arr = array();

        $check_result = FormatValidator::from($username)
            ->isNotEmpty(3, "手机号不能为空")
            ->isMobile(4, "请填入有效的手机号")
            ->validate();
        if($check_result){
            $result_arr = array(
                'code'=>$check_result["code"],
                'msg'=>$check_result["message"]
            );
            return response()->json($result_arr);
        }

		if(empty($password) || empty($code) || empty($nickname)){
			$result_arr = array(
					'code'=>2,
					'msg'=>'所有字段不能为空'
			);
		}else{
			$codeRows = DB::table('verify_code')->where("username", "=", $username)->orderBy('id','desc')->get();
			if(count($codeRows) == 0){
				$result_arr = array(
						'code'=>1,
						'msg'=>'验证码错误'
				);
			}else{
				$codeRow = $codeRows[0];
				if($code != $codeRow->code){
					$result_arr = array(
							'code'=>3,
							'msg'=>'验证码错误'
					);
				}else{
					$users = DB::table('users')->where("username", "=", $username)->get();
					if(count($users) != 0){
						$result_arr = array(
								'code'=>4,
								'msg'=>'用户已存在'
						);
					}else{
						$sid = $this->guid();
						$newId = DB::table('users')->insertGetId([
								'username'=>$username,
								'password'=>$password,
								'realname'=>$nickname,
								'sid' => $sid
						]);
                        $users = DB::table('users')->where("username", "=", $username)->get();
                        if(empty($users[0]->extra1)) {
                            $users[0]->extra1 = array();
                        }
                        $users[0]->extra1["avatar"] = $users[0]->extra2;
                        $users[0]->extra1["realname"] = $users[0]->realname;

                        $imageUrl = UserMgmrController::getImageUrl($request, $users[0]->extra2);

                        $result_arr = array(
                            'code'=>0,
                            'msg'=>'ok',
                            'result'=>array(
//                                'info'=>$users[0]->extra1,
                                'id'=>$users[0]->id,
                                'sid'=>$users[0]->sid,
                                'username'=>$users[0]->username,
                                'company'=>$users[0]->company,
                                'realname'=>$users[0]->realname,
                                'avatar'=>$imageUrl,
                            )
                        );

//						$result_arr = array(
//								'code'=>0,
//								'msg'=>'ok',
//								'result'=>array(
//										'sid'=>$sid,
//                                        'id'=>$newId
//								)
//						);
					}
				}
			}


		}
		return response()->json($result_arr);
	}


    public function updateUserInfo(Request $request){

        //check login
        $sid = $request->header('sid');
        if(empty($sid)){
            $result_arr = array(
                'code'=>1,
                'msg'=>'未登录，sid为空'
            );
            return response()->json($result_arr);
        }else{
            $users = DB::table('users')->where("sid", "=", $sid)->get();
            if(count($users) == 0){
                $result_arr = array(
                    'code'=>2,
                    'msg'=>'用户不存在'
                );
                return response()->json($result_arr);
            }
        }


        $data = $request->input('data');
        $user_id = $request->input('user_id');

        $result_arr = array();

        if(empty($data) || empty($user_id)){
            $result_arr = array(
                'code'=>2,
                'msg'=>'所有字段不能为空'
            );
        }else{
            $users = DB::table('users')->where("id", "=", $user_id)->get();
            if(count($users) == 0){
                $result_arr = array(
                    'code'=>3,
                    'msg'=>'用户不存在'
                );
            }else{
                DB::update('update users set extra1 = ? where id = ?',[$data, $user_id]);
                $result_arr = array(
                    'code'=>0,
                    'msg'=>'ok'
                );
            }


        }
        return response()->json($result_arr);
    }

    public function changeAvatar(Request $request)
    {

        $sid = $request->header('sid');
        if(empty($sid)){
            $sid = $request->input('sid');
        }

        if(empty($sid)){
            $result_arr = array(
                'code'=>1,
                'msg'=>'未登录'
            );
            return response()->json($result_arr);
        }else{
            $users = DB::table('users')->where("sid", "=", $sid)->get();
            if(count($users) == 0){
                $result_arr = array(
                    'code'=>2,
                    'msg'=>'用户不存在'
                );
                return response()->json($result_arr);
            }
        }


        $user_id = $request->input('user_id');
        if(empty($user_id)){
            $result_arr = array(
                'code'=>3,
                'msg'=>'user_id必传'
            );
            return response()->json($result_arr);
        }else{
            $users = DB::table('users')->where("id", "=", $user_id)->get();
            if(count($users) == 0){
                $result_arr = array(
                    'code'=>4,
                    'msg'=>'用户不存在'
                );
                return response()->json($result_arr);
            }else{

                try{
                    $destinationPath = 'uploads/';
                    // 取到图片
                    $file = $request->file('avatar');
                    if(!$file){
                        $result_arr = array(
                            'code'=>6,
                            'msg'=>'请务必以multipart的方式上传一个name为avatar的文件'
                        );
                        return response()->json($result_arr);
                    }
                    // 获得图片的名称 为了保证不重复 我们加上userid和time
//                    $file_name = 'avatar_' . $user_id . '_' . time() . $file->getClientOriginalName();
                    $file_name = 'avatar_' . $user_id . '_' . time() . time() . ".png";
                    // 执行move方法
                    $file->move($destinationPath, $file_name);

                    DB::update('update users set extra2 = ? where id = ?',[$destinationPath . $file_name, $user_id]);
//                    $imageUrl = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . "/" . $destinationPath . $file_name;
//                    $imageUrl = str_replace("/index.php", "", $imageUrl);

                    $imageUrl = UserMgmrController::getImageUrl($request, $destinationPath . $file_name);

                    $result_arr = array(
                        'code'=>0,
                        'msg'=>'ok',
                        'result'=>array(
                            'url'=> $imageUrl
                        )
                    );
                    //请求是：http://localhost:7888/tt201801/public/index.php/
                    //$request->getSchemeAndHttpHost()值是：  http://localhost:7888
                    //$request->getBaseUrl()值是：   /tt201801/public/index.php


                    //要的是：http://localhost:7888/tt201801/public/uploads/avatar_3_1518111944desktt.jpg

                    return response()->json($result_arr);
                }catch (Exception $e){
                    $result_arr = array(
                        'code'=>5,
                        'msg'=>'未知错误'
                    );
                    return response()->json($result_arr);
                }

            }
        }

    }

	public function login(Request $request){
		$username = $request->input('username');
		$password = $request->input('password');

		$result_arr = array();

        $check_result = FormatValidator::from($username)
            ->isNotEmpty(3, "手机号不能为空")
            ->isMobile(4, "请填入有效的手机号")
            ->validate();
        if($check_result){
            $result_arr = array(
                'code'=>$check_result["code"],
                'msg'=>$check_result["message"]
            );
            return response()->json($result_arr);
        }

		if(empty($password)){
			$result_arr = array(
					'code'=>2,
					'msg'=>'所有字段不能为空'
			);
		}else{
			$users = DB::table('users')->where("username", "=", $username)->get();
			if(count($users) == 0){
				$result_arr = array(
						'code'=>1,
						'msg'=>'用户不存在'
				);
			}else{
				$user = $users[0];
				if($user->password != $password){
					$result_arr = array(
							'code'=>3,
							'msg'=>'密码错误'
					);
				}else{
				    if(empty($user->extra1)) {
                        $user->extra1 = array();
                    }
                    $user->extra1["avatar"] = $user->extra2;
                    $imageUrl = UserMgmrController::getImageUrl($request, $user->extra2);

                    $result_arr = array(
							'code'=>0,
							'msg'=>'ok',
							'result'=>array(
//                               'info'=>$user->extra1,
                                'id'=>$user->id,
                                'sid'=>$user->sid,
                                'username'=>$user->username,
                                'company'=>$user->company,
                                'realname'=>$user->realname,
                                'avatar'=>$imageUrl,
							)
					);
				}

			}
		}
		return response()->json($result_arr);
	}


	public function systemMessage(Request $request){
        $currentUser = null;
        $auth = $this->handleAuth($request);
        if($auth){
            $result_arr = array(
                'code'=>$auth["code"],
                'msg'=>$auth["message"]
            );
            return response()->json($result_arr);
        }else{
            $currentUser = $this->getCurrentUser();
        }

        $db = PDOManager::getDB();
        $sql = "select * from contact where user_id=:user_id";
        $tasks = PDOManager::findAll($db, $sql, array(
            "user_id"=>$currentUser->id,
        ));
        if(Lang2::isEmpty($tasks)){
            $result_arr = array(
                'code'=>0,
                'msg'=>'',
                'result' => array()
            );
            return response()->json($result_arr);
        }

        $res = array();
        foreach ($tasks as $taskkkk){
            if(empty($taskkkk["birthday"])){
                continue;
            }
            $today = date('Y-m-d');
            if($today == $taskkkk["birthday"]){
                $res[] = array("content"=>"今天是" . $taskkkk["real_name"] . "生日");
            }else{
                continue;
            }
        }

        $result_arr = array(
            'code'=>0,
            'msg'=>'',
            'result' => $res,
        );
        return response()->json($result_arr);
    }

    public function regist(Request $request){

    	$username = $request->input('username');
    	$password = $request->input('password');
		$company = $request->input('company');
		$realname = $request->input('realname');

		$result_arr = array();

		if(empty($username) || empty($password) || empty($company) || empty($realname)){
			$result_arr = array(
					'code'=>2,
					'msg'=>'所有字段不能为空'
			);
		}else{
			$userCount = DB::table('users')->where("username", "=", $username)->count();
			if($userCount > 0){
				//用户名重复
				$result_arr = array(
						'code'=>1,
						'msg'=>'用户名重复--'.$username
				);
			}else{
				$sid = $this->guid();
				DB::table('users')->insert([
						'username'=>$username,
						'password'=>$password,
						'company'=>$company,
						'realname'=>$realname,
						'sid' => $sid
				]);
				$result_arr = array(
						'code'=>0,
						'msg'=>'ok',
						'result'=>array(
								'sid'=>$sid
						)
				);
			}
		}

    	//return response(json_encode($result_arr));
		return response()->json($result_arr);
		
    }

    public function logout(Request $request){
        $sid = $request->input('sid');

        $result_arr = array(
            'code'=>0,
            'msg'=>'ok'
        );
        return response()->json($result_arr);
    }


	public function delete(Request $request){
		$sid = $request->input('sid');
		$taskId = $request->input('taskId');
		$bywho = $request->input('bywho');

		$result_arr = array();

		if(empty($sid)){
			$result_arr = array(
					'code'=>1,
					'msg'=>'未登录，sid为空'
			);
			return response()->json($result_arr);
		}

		if(empty($taskId)){
			//新建
			$result_arr = array(
					'code'=>1,
					'msg'=>'必须指定要删除的id'
			);
			return response()->json($result_arr);

		}else{
			//update--结束
			DB::table('users')->where('id','=', $taskId)->delete();
			$result_arr = array(
					'code'=>0,
					'msg'=>'ok',
					'result'=>array()
			);
		}

		return response()->json($result_arr);
	}

	function guid(){
		if (function_exists('com_create_guid')){
			return com_create_guid();
		}else{
			mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45);// "-"
			$uuid = chr(123)// "{"
					.substr($charid, 0, 8).$hyphen
					.substr($charid, 8, 4).$hyphen
					.substr($charid,12, 4).$hyphen
					.substr($charid,16, 4).$hyphen
					.substr($charid,20,12)
					.chr(125);// "}"
			return $uuid;
		}
	}

	public static function getImageUrl($request, $subUrl){
	    if(empty($subUrl)){
	        return "";
        }
        $imageUrl = $request->getSchemeAndHttpHost() . $request->getBaseUrl() . "/" . $subUrl;
        $imageUrl = str_replace("/index.php", "", $imageUrl);
        return $imageUrl;
    }
}

?>